package com.wust.modules.poi.excel.imports;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.wust.modules.poi.excel.entity.params.ExcelImportEntity;
import com.wust.modules.poi.excel.entity.sax.SaxReadCellEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import com.wust.modules.poi.exception.excel.ExcelImportException;
import com.wust.modules.poi.exception.excel.enums.ExcelImportEnum;
import com.wust.modules.poi.handler.inter.IExcelDataHandler;
import com.wust.modules.poi.util.ExcelUtil;
import com.wust.modules.poi.util.PoiPublicUtil;

/**
 * @author wanheng
 */
@Slf4j
public class CellValueServer {

    private List<String> handlerList = null;

    private Object getCellValue(String xclass, Cell cell, ExcelImportEntity entity) {
        if (cell == null) {
            return "";
        } else {
            Object result = null;
            if (!"class java.util.Date".equals(xclass) && !"class java.sql.Time".equals(xclass)) {
                if (0 == cell.getCellType()) {
                    result = cell.getNumericCellValue();
                } else if (4 == cell.getCellType()) {
                    result = cell.getBooleanCellValue();
                } else {
                    result = cell.getStringCellValue();
                }
            } else {
                if (0 == cell.getCellType()) {
                    result = cell.getDateCellValue();
                } else {
                    cell.setCellType(1);
                    result = this.getDateData(entity, cell.getStringCellValue());
                }

                if ("class java.sql.Time".equals(xclass)) {
                    result = new Time(((Date)result).getTime());
                }
            }

            return result;
        }
    }

    private Date getDateData(ExcelImportEntity entity, String value) {
        if (StringUtils.isNotEmpty(entity.getFormat()) && StringUtils.isNotEmpty(value)) {
            SimpleDateFormat format = new SimpleDateFormat(entity.getFormat());

            try {
                return format.parse(value);
            } catch (ParseException e) {
                log.error("时间格式化失败,格式化:{},值:{}", entity.getFormat(), value);
                throw new ExcelImportException(ExcelImportEnum.GET_VALUE_ERROR);
            }
        } else {
            return null;
        }
    }

    public Object getValue(IExcelDataHandler dataHanlder, Object object, Cell cell, Map<String, ExcelImportEntity> excelParams, String titleString) throws Exception {
        ExcelImportEntity entity = (ExcelImportEntity)excelParams.get(titleString);
        String xclass = "class java.lang.Object";
        if (!(object instanceof Map)) {
            Method setMethod = entity.getMethods() != null && entity.getMethods().size() > 0 ? (Method)entity.getMethods().get(entity.getMethods().size() - 1) : entity.getMethod();
            Type[] ts = setMethod.getGenericParameterTypes();
            xclass = ts[0].toString();
        }

        Object result = this.getCellValue(xclass, cell, entity);
        if (entity != null) {
            result = this.hanlderSuffix(entity.getSuffix(), result);
            result = this.replaceValue(entity.getReplace(), result, entity.isMultiReplace());
        }

        result = this.hanlderValue(dataHanlder, object, result, titleString);
        return this.getValueByType(xclass, result, entity);
    }

    public Object getValue(IExcelDataHandler dataHanlder, Object object, SaxReadCellEntity cellEntity, Map<String, ExcelImportEntity> excelParams, String titleString) {
        ExcelImportEntity entity = (ExcelImportEntity)excelParams.get(titleString);
        Method setMethod = entity.getMethods() != null && entity.getMethods().size() > 0 ? (Method)entity.getMethods().get(entity.getMethods().size() - 1) : entity.getMethod();
        Type[] ts = setMethod.getGenericParameterTypes();
        String xclass = ts[0].toString();
        Object result = cellEntity.getValue();
        result = this.hanlderSuffix(entity.getSuffix(), result);
        result = this.replaceValue(entity.getReplace(), result, entity.isMultiReplace());
        result = this.hanlderValue(dataHanlder, object, result, titleString);
        return this.getValueByType(xclass, result, entity);
    }

    private Object hanlderSuffix(String suffix, Object result) {
        if (StringUtils.isNotEmpty(suffix) && result != null && result.toString().endsWith(suffix)) {
            String temp = result.toString();
            return temp.substring(0, temp.length() - suffix.length());
        } else {
            return result;
        }
    }

    private Object getValueByType(String xclass, Object result, ExcelImportEntity entity) {
        try {
            if (result != null && !"".equals(String.valueOf(result))) {
                if ("class java.util.Date".equals(xclass)) {
                    return result;
                } else if (!"class java.lang.Boolean".equals(xclass) && !"boolean".equals(xclass)) {
                    if (!"class java.lang.Double".equals(xclass) && !"double".equals(xclass)) {
                        if (!"class java.lang.Long".equals(xclass) && !"long".equals(xclass)) {
                            if (!"class java.lang.Float".equals(xclass) && !"float".equals(xclass)) {
                                if (!"class java.lang.Integer".equals(xclass) && !"int".equals(xclass)) {
                                    if ("class java.math.BigDecimal".equals(xclass)) {
                                        return new BigDecimal(String.valueOf(result));
                                    } else if ("class java.lang.String".equals(xclass)) {
                                        if (result instanceof String) {
                                            return ExcelUtil.remove0Suffix(result);
                                        } else {
                                            return result instanceof Double ? PoiPublicUtil.doubleToString((Double)result) : ExcelUtil.remove0Suffix(String.valueOf(result));
                                        }
                                    } else {
                                        return result;
                                    }
                                } else {
                                    return Integer.valueOf(ExcelUtil.remove0Suffix(String.valueOf(result)));
                                }
                            } else {
                                return Float.valueOf(String.valueOf(result));
                            }
                        } else {
                            return Long.valueOf(ExcelUtil.remove0Suffix(String.valueOf(result)));
                        }
                    } else {
                        return Double.valueOf(String.valueOf(result));
                    }
                } else {
                    return Boolean.valueOf(String.valueOf(result));
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ExcelImportException(ExcelImportEnum.GET_VALUE_ERROR);
        }
    }

    private Object hanlderValue(IExcelDataHandler dataHanlder, Object object, Object result, String titleString) {
        if (dataHanlder != null && dataHanlder.getNeedHandlerFields() != null && dataHanlder.getNeedHandlerFields().length != 0) {
            if (this.handlerList == null) {
                this.handlerList = Arrays.asList(dataHanlder.getNeedHandlerFields());
            }

            return this.handlerList.contains(titleString) ? dataHanlder.importHandler(object, titleString, result) : result;
        } else {
            return result;
        }
    }

    private Object replaceValue(String[] replace, Object result, boolean multiReplace) {
        if (result == null) {
            return "";
        } else if (replace != null && replace.length > 0) {
            String temp = String.valueOf(result);
            String backValue = "";
            if (temp.indexOf(",") > 0 && multiReplace) {
                String[] multiReplaces = temp.split(",");
                String[] multiReplaces1 = multiReplaces;
                int length = multiReplaces.length;

                for(int i = 0; i < length; ++i) {
                    String str = multiReplaces1[i];
                    backValue = backValue.concat(this.replaceSingleValue(replace, str) + ",");
                }

                if ("".equals(backValue)) {
                    backValue = temp;
                } else {
                    backValue = backValue.substring(0, backValue.length() - 1);
                }
            } else {
                backValue = this.replaceSingleValue(replace, temp);
            }

            return backValue;
        } else {
            return result;
        }
    }

    private String replaceSingleValue(String[] replace, String temp) {
        for(int i = 0; i < replace.length; ++i) {
            String[] tempArr = replace[i].split("_");
            if (temp.equals(tempArr[0])) {
                return tempArr[1];
            }
        }

        return temp;
    }
}
